package io.renren.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import io.renren.common.exception.RRException;
import io.renren.common.utils.IPUtils;
import io.renren.config.ApiConfig;
import io.renren.util.ApiResult;
import io.renren.util.JwtUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;

/**
 * ClassName: ApiBaseController
 * Description:
 * date: 2020/1/24 9:23
 *
 * @author afeng
 * @since JDK 1.8
 */
public class ApiBaseController {

    @Autowired
    public HttpServletRequest request;

    @Autowired
    public HttpServletResponse response;

    /**
     * 获取键值对参数
     */
    public String getParameter(String key) {
        return request.getParameter(key);
    }

    /**
     * 获取流参数，如json、xml
     */
    public String getBufferParam() {
        String param = null;
        try (BufferedReader streamReader = new BufferedReader(new InputStreamReader(request.getInputStream(), StandardCharsets.UTF_8))) {
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = streamReader.readLine()) != null) {
                sb.append(line);
            }
            if (sb.length() < 1) {
                return "";
            }
            param = sb.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return param;
    }

    /**
     * 获取JSON参数并格式化为对象
     */
    public <T> T getFromJson(Class<T> klass) {
        String jsonStr = getBufferParam();
        if (StringUtils.isEmpty(jsonStr)) {
            return null;
        }
        JSONObject json = JSONObject.parseObject(jsonStr);
        return JSON.toJavaObject(json, klass);
    }

    /**
     * 获取客户端ip
     */
    public String getRealIp() {
        return IPUtils.getIpAddr(request);
    }

    /**
     * 获取客户端token
     */
    public String getToken() {
        return request.getHeader("Authorization");
    }

    /**
     * 根据token获取用户id，如果不存在则抛出异常
     */
    public String getUserId() {
        String token = getToken();
        String userId = JwtUtil.queryByToken(ApiConfig.TOKEN_KEY, token);
        if (StringUtils.isBlank(userId)) {
            throw new RRException("用户不存在");
        }
        return userId;
    }


    /**
     * 返回成功消息
     */
    public ApiResult success(Object data) {
        return ApiResult.success(data);
    }

    public ApiResult success(String msg, Object data) {
        return ApiResult.success(msg, data);
    }

    public ApiResult success() {
        return ApiResult.success();
    }

    public ApiResult success(String message) {
        return ApiResult.success(message);
    }

    /**
     * 返回失败消息
     */
    public ApiResult error() {
        return ApiResult.error();
    }

    public ApiResult error(String message) {
        return ApiResult.error(message);
    }

    public ApiResult error(ApiResult.Type type, String message) {
        return new ApiResult(type, message);
    }


}
